package com.tduck.cloud.api.web.controller.system;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.tduck.cloud.common.entity.security.LoginUserEntity;
import com.tduck.cloud.common.entity.security.SysUserVO;
import com.tduck.cloud.common.util.ServletUtils;
import com.tduck.cloud.common.util.Result;
import com.tduck.cloud.security.service.TokenService;
import com.tduck.cloud.storage.cloud.OssStorageFactory;
import com.tduck.cloud.system.constant.UserConstants;
import com.tduck.cloud.system.entity.SysUserEntity;
import com.tduck.cloud.system.service.SysUserService;
import com.tduck.cloud.common.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 个人信息
 *
 * @author smalljop
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/user/profile")
public class SysProfileController {
    private final SysUserService userService;

    private final TokenService tokenService;

    /**
     * 获取个人信息
     */
    @GetMapping
    public Result profile() {
        LoginUserEntity loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUserVO user = loginUser.getUser();
        Map<String, Object> result = new HashMap<>(2);
        result.put("user", user);
        result.put("roleGroup", userService.getUserRoleGroup(loginUser.getUsername()));
        result.put("postGroup", userService.getUserPostGroup(loginUser.getUsername()));
        return Result.success(result);
    }

    /**
     * 修改用户
     */
    @PutMapping
    public Result updateProfile(@RequestBody SysUserEntity user) {
        if (StrUtil.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return Result.failed("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StrUtil.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return Result.failed("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(user) > 0) {
            LoginUserEntity loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginUser.getUser().setNickName(user.getNickName());
            loginUser.getUser().setPhonenumber(user.getPhonenumber());
            loginUser.getUser().setEmail(user.getEmail());
            loginUser.getUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return Result.success();
        }
        return Result.failed("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @PostMapping("/updatePwd")
    public Result updatePwd(String oldPassword, String newPassword) {
        LoginUserEntity loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return Result.failed("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return Result.failed("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return Result.success();
        }
        return Result.failed("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public Result avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            String path = new StringBuffer("avatar")
                    .append(IdUtil.simpleUUID())
                    .append(CharUtil.DOT)
                    .append(FileUtil.extName(file.getOriginalFilename())).toString();
            String avatar = OssStorageFactory.getStorageService().upload(file.getInputStream(), path);
            LoginUserEntity loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
                Map<String, Object> ajax = new HashMap<>();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return Result.success(ajax);
            }
        }
        return Result.failed("上传图片异常，请联系管理员");
    }
}
